<template>
  <div class="dream-interpreter" :class="currentTheme">
    <!-- 应用介绍 -->
    <div class="app-intro">
      <h1>AI梦境解析器</h1>
      <p>输入昨晚的梦境，AI将用多种风格为您解析</p>
      <p>弗洛伊德心理学 + 玄学 + 赛博朋克风格解析</p>
      <p>并生成一张超现实插画展示您的梦境</p>
    </div>
    
    <!-- 用户输入模块 -->
    <div class="icons">
      <span class="theme-icon" @click="selectTheme('theme-default')">🌙</span>
      <span class="theme-icon" @click="selectTheme('theme-mystic')">✨</span>
      <span class="theme-icon" @click="selectTheme('theme-cyber')">🤖</span>
    </div>
    
    <div class="input-section">
      <div class="input-container">
        <textarea 
          ref="inputField"
          v-model="dreamContent"
          @input="handleInput"
          placeholder="请描述您的梦境，例如：梦见会飞的鱼..."
          maxlength="500"
          class="dream-input"
        ></textarea>
        <span class="char-counter">{{ dreamContent.length }}/500</span>
      </div>
      
      <div class="style-selector">
        <span>解析流派：</span>
        <select v-model="selectedStyle">
          <option value="all">全部风格</option>
          <option value="psychology">弗洛伊德心理学</option>
          <option value="mystic">东方玄学</option>
          <option value="cyber">赛博朋克AI</option>
        </select>
      </div>
      
      <div class="button-group">
        <button 
          @click="interpretDream" 
          :disabled="!dreamContent"
          class="interpret-btn"
        >
          解析梦境
        </button>
        <button 
          @click="useExample" 
          class="example-btn"
        >
          使用示例
        </button>
      </div>
    </div>

    <!-- 遮罩层 -->
    <div v-if="loading" class="overlay">
      <div class="loading-spinner">正在解析梦境...</div>
    </div>

    <!-- 结果展示 -->
    <div v-if="interpretation" class="result-section">
      <div class="dream-image" v-if="dreamImage">
        <img :src="dreamImage" alt="梦境视觉化" />
      </div>
      
      <div v-if="showPsychology" class="interpretation psychology">
        <h3>🧠 弗洛伊德心理学解析</h3>
        <div v-html="interpretation.psychology"></div>
      </div>
      
      <div v-if="showMystic" class="interpretation mystic">
        <h3>🔮 东方玄学解析</h3>
        <div v-html="interpretation.mystic"></div>
      </div>
      
      <div v-if="showCyber" class="interpretation cyber">
        <h3>🤖 赛博朋克AI解析</h3>
        <div v-html="interpretation.cyber"></div>
      </div>
      
      <div class="action-buttons">
        <button @click="saveToMuseum" class="save-btn">收藏到梦境博物馆</button>
        <button @click="shareDream" class="share-btn">分享解析</button>
      </div>
    </div>
    
    <!-- 错误提示 -->
    <div v-if="error" class="error-toast">
      {{ error }}
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { marked } from 'marked';

export default {
  name: 'DreamInterpreter',
  data() {
    return {
      currentTheme: localStorage.getItem('dreamTheme') || 'theme-default',
      dreamContent: '',
      selectedStyle: 'all',
      loading: false,
      interpretation: null,
      dreamImage: null,
      error: null,
      dreamMuseum: [],
      exampleDreams: [
        '梦见自己在海底行走，周围有会飞的鱼，它们发出彩色的光芒',
        '梦见自己变成了一棵树，能感受到阳光和雨水',
        '梦见在一座空城里奔跑，追逐着一个永远看不清脸的人'
      ]
    }
  },
  computed: {
    showPsychology() {
      return this.selectedStyle === 'all' || this.selectedStyle === 'psychology';
    },
    showMystic() {
      return this.selectedStyle === 'all' || this.selectedStyle === 'mystic';
    },
    showCyber() {
      return this.selectedStyle === 'all' || this.selectedStyle === 'cyber';
    }
  },
  mounted() {
    this.$refs.inputField.focus();
    this.loadMuseum();
  },
  methods: {
    selectTheme(theme) {
      this.currentTheme = theme;
      localStorage.setItem('dreamTheme', theme);
    },
    handleInput() {
      if (this.dreamContent.length > 500) {
        this.dreamContent = this.dreamContent.substring(0, 500);
      }
    },
    useExample() {
      const randomIndex = Math.floor(Math.random() * this.exampleDreams.length);
      this.dreamContent = this.exampleDreams[randomIndex];
    },
    async interpretDream() {
      if (!this.dreamContent) return;
      
      this.loading = true;
      this.error = null;
      
      try {
        // 调用大模型API解析梦境
        const interpretationResult = await this.callInterpretationAPI();
        this.interpretation = interpretationResult;
        
        // 生成梦境图像
        try {
          const imageUrl = await this.generateDreamImage();
          this.dreamImage = imageUrl;
        } catch (imgError) {
          console.error('梦境图像生成失败:', imgError);
          this.dreamImage = null;
        }
      } catch (error) {
        this.showError(error.message || '网络连接失败，请重试');
      } finally {
        this.loading = false;
      }
    },
    async callInterpretationAPI() {
      try {
        const response = await axios.post('https://api.siliconflow.cn/v1/chat/completions', {
          model: 'Qwen/QwQ-32B',
          messages: [{
            role: 'user',
            content: `请以三种不同风格解析这个梦境：${this.dreamContent}。
            1. 弗洛伊德心理学风格解析
            2. 东方玄学风格解析
            3. 赛博朋克AI风格解析
            请用markdown格式输出，每种解析200-300字。`
          }],
          stream: false,
          max_tokens: 1024,
          temperature: 0.7
        }, {
          headers: {
            Authorization: 'Bearer ' + process.env.VUE_APP_API_KEY,
            'Content-Type': 'application/json'
          }
        });
        
        const content = response.data.choices[0].message.content;
        
        // 解析返回的内容，提取三种解析
        const psychologyMatch = content.match(/弗洛伊德心理学风格解析[\s\S]*?(?=东方玄学风格解析|$)/i);
        const mysticMatch = content.match(/东方玄学风格解析[\s\S]*?(?=赛博朋克AI风格解析|$)/i);
        const cyberMatch = content.match(/赛博朋克AI风格解析[\s\S]*?$/i);
        
        return {
          psychology: psychologyMatch ? marked(psychologyMatch[0]) : '解析生成失败',
          mystic: mysticMatch ? marked(mysticMatch[0]) : '解析生成失败',
          cyber: cyberMatch ? marked(cyberMatch[0]) : '解析生成失败'
        };
      } catch (error) {
        throw new Error('梦境解析失败: ' + error.message);
      }
    },
    async generateDreamImage() {
      try {
        const response = await axios.post('https://api.siliconflow.cn/v1/images/generations', {
          model: 'Kwai-Kolors/Kolors',
          prompt: `超现实主义风格插画，描绘梦境场景：${this.dreamContent}，梦幻般的色彩，超现实元素，细节丰富`,
          negative_prompt: '模糊，扭曲，低质量',
          image_size: '1024x1024',
          batch_size: 1,
          seed: Math.floor(Math.random() * 1000000000),
          num_inference_steps: 30,
          guidance_scale: 7.5
        }, {
          headers: {
            Authorization: 'Bearer ' + process.env.VUE_APP_API_KEY,
            'Content-Type': 'application/json'
          }
        });
        
        if (response.data.images && response.data.images.length > 0) {
          return response.data.images[0].url;
        }
        return null;
      } catch (error) {
        console.error('图片生成失败:', error);
        return null;
      }
    },
    showError(message) {
      this.error = message;
      setTimeout(() => {
        this.error = null;
      }, 3000);
    },
    saveToMuseum() {
      if (!this.interpretation || !this.dreamContent) return;
      
      const dreamRecord = {
        id: Date.now(),
        date: new Date().toLocaleString(),
        content: this.dreamContent,
        interpretation: this.interpretation,
        imageUrl: this.dreamImage
      };
      
      this.dreamMuseum.unshift(dreamRecord);
      if (this.dreamMuseum.length > 10) {
        this.dreamMuseum.pop();
      }
      
      localStorage.setItem('dreamMuseum', JSON.stringify(this.dreamMuseum));
      this.showError('已收藏到梦境博物馆');
    },
    loadMuseum() {
      const saved = localStorage.getItem('dreamMuseum');
      if (saved) {
        this.dreamMuseum = JSON.parse(saved);
      }
    },
    shareDream() {
      alert('分享功能: 梦境解析分享');
    }
  }
}
</script>

<style scoped>
/* 主题样式 */
.dream-interpreter.theme-default {
  background-color: #1a1a2e;
  color: #e6e6e6;
}

.dream-interpreter.theme-mystic {
  background-color: #2d1b4e;
  color: #e6e6e6;
}

.dream-interpreter.theme-cyber {
  background-color: #0f0f23;
  color: #00ff9d;
}

.dream-interpreter {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Roboto', sans-serif;
  min-height: 100vh;
}

.app-intro {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background-color: rgba(255,255,255,0.1);
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.3);
}

.app-intro h1 {
  color: #9d4edd;
  margin-bottom: 15px;
}

.app-intro p {
  margin: 8px 0;
  line-height: 1.6;
}

.icons {
  text-align: center;
  margin-bottom: 20px;
}

.theme-icon {
  font-size: 24px;
  cursor: pointer;
  margin: 0 10px;
  transition: transform 0.3s;
}

.theme-icon:hover {
  transform: scale(1.2);
}

.input-section {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;
}

.input-container {
  position: relative;
}

.dream-input {
  width: 100%;
  height: 150px;
  padding: 15px;
  border: 2px solid #9d4edd;
  border-radius: 8px;
  font-size: 16px;
  background-color: rgba(255, 255, 255, 0.1);
  color: inherit;
  resize: none;
}

.dream-input:focus {
  outline: none;
  border-color: #c77dff;
  box-shadow: 0 0 0 2px rgba(157, 78, 221, 0.2);
}

.char-counter {
  position: absolute;
  right: 15px;
  bottom: 15px;
  color: #888;
  font-size: 14px;
}

.style-selector {
  display: flex;
  align-items: center;
  gap: 10px;
}

.style-selector select {
  padding: 8px 12px;
  border-radius: 6px;
  border: 1px solid #9d4edd;
  background-color: rgba(255, 255, 255, 0.1);
  color: inherit;
}

.button-group {
  display: flex;
  gap: 15px;
  margin-top: 10px;
}

.interpret-btn, .example-btn {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
  flex: 1;
}

.interpret-btn {
  background-color: #9d4edd;
  color: white;
}

.interpret-btn:hover {
  background-color: #7b2cbf;
}

.interpret-btn:disabled {
  background-color: #666;
  cursor: not-allowed;
}

.example-btn {
  background-color: #3a0ca3;
  color: white;
}

.example-btn:hover {
  background-color: #240046;
}

.overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.loading-spinner {
  background-color: rgba(0, 0, 0, 0.8);
  color: #9d4edd;
  padding: 20px 30px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
}

.result-section {
  margin-top: 30px;
  animation: fadeIn 0.5s;
}

.dream-image {
  margin-bottom: 20px;
  text-align: center;
}

.dream-image img {
  max-width: 100%;
  border-radius: 8px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
}

.interpretation {
  margin: 20px 0;
  padding: 20px;
  border-radius: 8px;
}

.interpretation h3 {
  margin-bottom: 15px;
}

.psychology {
  background-color: rgba(157, 78, 221, 0.1);
  border-left: 4px solid #9d4edd;
}

.mystic {
  background-color: rgba(255, 138, 0, 0.1);
  border-left: 4px solid #ff8a00;
}

.cyber {
  background-color: rgba(0, 255, 157, 0.1);
  border-left: 4px solid #00ff9d;
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin-top: 30px;
}

.save-btn, .share-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  flex: 1;
}

.save-btn {
  background-color: #3a0ca3;
  color: white;
}

.save-btn:hover {
  background-color: #240046;
}

.share-btn {
  background-color: #7209b7;
  color: white;
}

.share-btn:hover {
  background-color: #560bad;
}

.error-toast {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: #d90429;
  color: white;
  padding: 12px 24px;
  border-radius: 4px;
  box-shadow: 0 3px 5px rgba(0, 0, 0, 0.2);
  z-index: 1000;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@media (max-width: 600px) {
  .dream-interpreter {
    padding: 15px;
  }
  
  .button-group {
    flex-direction: column;
  }
}
</style>